package com.demo.mydictdemo;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private ContentResolver resolver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        resolver = getContentResolver();

        final EditText word = (EditText) findViewById(R.id.word);
        final EditText detail = (EditText) findViewById(R.id.detail);
        final EditText search = (EditText) findViewById(R.id.key);
        Button btnInsert = (Button) findViewById(R.id.insert);
        Button btnSearch = (Button) findViewById(R.id.search);

        btnInsert.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // 构造记录的内容ContentValues
                ContentValues values = new ContentValues();
                values.put(Words.Word.WORD, word.getText().toString());
                values.put(Words.Word.DETAIL, detail.getText().toString());
                // 插入dict表中
                resolver.insert(Words.Word.DICT_CONTENT_URI, values);
                word.setText("");
                detail.setText("");
            }
        });

        btnSearch.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // 查询word
                String key = search.getText().toString();
                Cursor cursor = resolver.query(Words.Word.DICT_CONTENT_URI, null, "word like ?", new String[]{"%" + key + "%"}, null);
                // 将Cursor数据转化为List<Map<String,String>>
                ArrayList<Map<String, String>> listData = new ArrayList<Map<String, String>>();
                while (cursor.moveToNext()) {
                    Map<String, String> item = new HashMap<String, String>();
                    item.put("word", cursor.getString(1));
                    item.put("detail", cursor.getString(2));
                    listData.add(item);
                }
                // 通过Intent启动ResultActivity，携带数据
                Intent intent = new Intent(MainActivity.this, ResultActivity.class);
                Bundle data = new Bundle();
                data.putSerializable("list", listData);
                intent.putExtras(data);
                startActivity(intent);
            }
        });
    }

}
